'use strict';
const Service = require('egg').Service;
const { Op } = require('sequelize');

const { failRes, successRes } = require('../extend/helper');
const { Journal } = require('../exception/Journal');

function toInt (str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sJournal extends Service {
  // pc
  // 查
  async pc_s_query (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const result = await ctx.model.Journal.findAndCountAll({
        where: {
          Ip: {
            [Op.like]: `%${(params?.Ip ?? '')}%`
          },
          Source: {
            [Op.like]: `%${(params?.Source ?? '')}%`
          },
          Type: {
            [Op.like]: `%${(params?.Type ?? '')}%`
          },
        },
        order: [['id', 'DESC']], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      })
      await Journal(ctx, { operatorType: '系统日志 -> 查询', code: 200 });
      response = successRes({
        records: (result?.rows ?? []),
        total: (result?.count ?? 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 系统日志查询');
      await Journal(ctx, { operatorType: '系统日志 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }
}

module.exports = sJournal;